import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../providers/project_provider.dart';
import '../../../domain/entities/project.dart';

/// 项目详情页面
class ProjectDetailPage extends ConsumerStatefulWidget {
  final int projectId;

  const ProjectDetailPage({
    super.key,
    required this.projectId,
  });

  @override
  ConsumerState<ProjectDetailPage> createState() => _ProjectDetailPageState();
}

class _ProjectDetailPageState extends ConsumerState<ProjectDetailPage> {
  @override
  void initState() {
    super.initState();
    // 加载项目详情
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(projectStateProvider.notifier).loadProject(widget.projectId);
    });
  }

  @override
  Widget build(BuildContext context) {
    final projectState = ref.watch(projectStateProvider);
    final currentProject = ref.watch(currentProjectProvider);

    return Scaffold(
      appBar: AppBar(
        title: SelectableText('项目详情 #${widget.projectId}'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          if (currentProject != null)
            IconButton(
              icon: const Icon(Icons.edit),
              onPressed: () {
                _showEditProjectDialog(context, currentProject);
              },
            ),
        ],
      ),
      body: _buildBody(projectState, currentProject),
    );
  }

  Widget _buildBody(ProjectState state, Project? project) {
    if (state is ProjectLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (state is ProjectError) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.red,
            ),
            const SizedBox(height: 16),
            SelectableText(
              '加载失败',
              style: Theme.of(context).textTheme.headlineSmall,
            ),
            const SizedBox(height: 8),
            SelectableText(
              state.message,
              style: Theme.of(context).textTheme.bodyMedium,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                ref
                    .read(projectStateProvider.notifier)
                    .loadProject(widget.projectId);
              },
              child: const SelectableText('重试'),
            ),
          ],
        ),
      );
    }

    if (project == null) {
      return const Center(
        child: SelectableText('项目不存在'),
      );
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 项目基本信息卡片
          _buildProjectInfoCard(project),
          const SizedBox(height: 16),

          // 项目统计信息
          _buildProjectStatsCard(project),
          const SizedBox(height: 16),

          // 项目描述
          _buildProjectDescriptionCard(project),
        ],
      ),
    );
  }

  Widget _buildProjectInfoCard(Project project) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.info_outline, color: Colors.blue),
                const SizedBox(width: 8),
                SelectableText(
                  '项目信息',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            _buildInfoRow('项目名称', project.projectName),
            _buildInfoRow('状态', project.status.description),
            _buildInfoRow('优先级', project.priority.description),
            _buildInfoRow('创建者', project.creatorName),
            _buildInfoRow('创建时间', _formatDateTime(project.createTime)),
            _buildInfoRow('更新时间', _formatDateTime(project.updateTime)),
            if (project.deadline != null)
              _buildInfoRow('截止时间', _formatDateTime(project.deadline!)),
          ],
        ),
      ),
    );
  }

  Widget _buildProjectStatsCard(Project project) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.analytics_outlined, color: Colors.green),
                const SizedBox(width: 8),
                SelectableText(
                  '项目统计',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            if (project.todoStats != null) ...[
              _buildStatsRow('总任务数', project.todoStats!.total.toString()),
              _buildStatsRow('已完成', project.todoStats!.completed.toString()),
              _buildStatsRow('进行中', project.todoStats!.inProgress.toString()),
              _buildStatsRow('待处理', project.todoStats!.todo.toString()),
              _buildStatsRow('已阻塞', project.todoStats!.blocked.toString()),
            ] else
              const SelectableText('暂无任务统计数据'),
          ],
        ),
      ),
    );
  }

  Widget _buildProjectDescriptionCard(Project project) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.description_outlined, color: Colors.orange),
                const SizedBox(width: 8),
                SelectableText(
                  '项目描述',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            SelectableText(
              project.description ?? '暂无描述',
              style: Theme.of(context).textTheme.bodyMedium,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: SelectableText(
              '$label:',
              style: const TextStyle(
                color: Colors.grey,
                fontSize: 14,
              ),
            ),
          ),
          Expanded(
            child: SelectableText(
              value,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatsRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SelectableText(
            label,
            style: const TextStyle(
              color: Colors.grey,
              fontSize: 14,
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
            decoration: BoxDecoration(
              color: Colors.blue.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: SelectableText(
              value,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                color: Colors.blue,
              ),
            ),
          ),
        ],
      ),
    );
  }

  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} '
        '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }

  void _showEditProjectDialog(BuildContext context, Project project) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('编辑项目'),
        content: const SelectableText('编辑项目功能开发中...'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: SelectableText('编辑项目功能开发中...')),
              );
            },
            child: const SelectableText('确定'),
          ),
        ],
      ),
    );
  }
}
